package com.stone.databinding.util;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.databinding.BindingConversion;
import androidx.databinding.InverseMethod;

import com.stone.databinding.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public final class ConverterUtil {
    public static boolean isZero(int val) {
        return val== 0;
    }

    @BindingConversion
    public static int booleanToVisibility(boolean visible) {
        return visible ? View.VISIBLE : View.GONE;
    }

    public static String fromTenthsToSeconds(int tenths) {
        if (tenths < 600) {
            return String.format("%.1f", tenths / 10.0);
        } else {
            int minutes = (tenths / 10) / 60;
            int seconds = (tenths / 10) % 60;
            return String.format("%d:%02d", minutes, seconds);
        }
    }

    public static int cleanSecondsString(String seconds) {
        // Remove letters and other characters
        String filteredValue = seconds.replace("[^d:.]", "");
        if (filteredValue.isEmpty())
            return 0;
        List<String> elements = Arrays.asList(filteredValue.split(":"));
        int result = 0;
        if (elements != null && elements.size() > 0) {
            if (elements.size() > 2) {
                return 0;
            } else if (elements.size() > 1) {
                try {
                    result = Integer.parseInt(elements.get(0)) * 60 + Integer.parseInt(elements.get(1));
                    result *= 10;
                } catch (NumberFormatException e) {
                    Log.e("Converter", "cleanSecondsString failed: " + e.getMessage());
                }
            }
        }
        return result;
    }

    /**
     * Used with `numberOfSets` to convert from array to String.
     */
    @InverseMethod("stringToSetArray")
    public static String setArrayToString(Context context, ArrayList<Integer> value) {
        return context.getString(R.string.sets_format, value.get(0) + 1, value.get(1));
    }

    /**
     * This is the Inverse Method used in `numberOfSets`, to convert from String to array.
     *
     * Note that Context is passed
     */
    public static ArrayList<Integer> stringToSetArray(Context context, String value) {
        ArrayList<Integer> result = new ArrayList<>();
        result.add(0);
        // Converts String to long
        if (value.isEmpty()) {
            result.add(0);
        } else {
            try {
                result.add(Integer.parseInt(value));
            } catch (NumberFormatException e) {
                Log.e("ConvertUtil", "stringToSetArray failed: " + e.getMessage());
                result.add(0);
            }
        }
        return result;
    }
}
